package com.example.uploadfilestoserver;

import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;

public class ThreadDownloadDemo extends Activity {

	private TextView downloadurl;
	private EditText downloadnum;
	private Button downloadbutton;
	private ProgressBar downloadProgressBar;
	private TextView downloadinfo;
	private int downloadedSize = 0;
	private int fileSize = 0;

	private long downloadtime;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.threaddemo);

		downloadurl = (TextView) findViewById(R.id.downloadurl);
		downloadurl
				.setText("http://pilatus.d1.comp.nus.edu.sg/~a0120575/video_repo/renren.mp3");
		downloadnum = (EditText) findViewById(R.id.downloadnum);
		downloadinfo = (TextView) findViewById(R.id.downloadinfo);
		downloadbutton = (Button) findViewById(R.id.downloadbutton);
		downloadProgressBar = (ProgressBar) findViewById(R.id.downloadProgressBar);
		downloadProgressBar.setVisibility(View.VISIBLE);
		downloadProgressBar.setMax(100);
		downloadProgressBar.setProgress(0);
		downloadbutton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				download();
				downloadtime = SystemClock.currentThreadTimeMillis();
			}
		});
	}

	private void download() {
		String url = downloadurl.getText().toString();
		// 取得最后一个/的下标
		int index = url.lastIndexOf("/");
		// 将字符串转为字符数组
		char[] ch = url.toCharArray();
		// 根据 copyValueOf(char[] data, int offset, int count) 取得最后一个字符串
		String lastString = String.copyValueOf(ch, index + 1, ch.length - index
				- 1);
		// 获取SD卡目录
		String dowloadDir = Environment.getExternalStorageDirectory()
				+ "/kate/";
		File file = new File(dowloadDir);
		// 创建下载目录
		if (!file.exists()) {
			file.mkdirs();
		}

		// 读取下载线程数，如果为空，则单线程下载
		int downloadTN = Integer.valueOf("".equals(downloadnum.getText()
				.toString()) ? "1" : downloadnum.getText().toString());
		String fileName = lastString;
		// 开始下载前把下载按钮设置为不可用
		downloadbutton.setClickable(false);
		// 进度条设为0
		downloadProgressBar.setProgress(0);
		// 启动文件下载线程
		new downloadTask(url, Integer.valueOf(downloadTN), dowloadDir
				+ fileName).start();
	}

	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// 当收到更新视图消息时，计算已完成下载百分比，同时更新进度条信息
			int progress = (Double
					.valueOf((downloadedSize * 1.0 / fileSize * 100)))
					.intValue();
			if (progress == 100) {
				downloadbutton.setClickable(true);
				downloadinfo.setText("下载完成！");
				Dialog mdialog = new AlertDialog.Builder(
						ThreadDownloadDemo.this)
						.setTitle("提示信息")
						.setMessage(
								"下载完成，总用时为:"
										+ (SystemClock
												.currentThreadTimeMillis() - downloadtime)
										+ "毫秒")
						.setNegativeButton("确定",
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										dialog.dismiss();
									}
								}).create();
				mdialog.show();
			} else {
				downloadinfo.setText("当前进度:" + progress + "%");
			}
			downloadProgressBar.setProgress(progress);
		}

	};

	public class downloadTask extends Thread {
		private int blockSize, downloadSizeMore;
		private int threadNum = 5;
		String urlStr, threadNo, fileName;

		public downloadTask(String urlStr, int threadNum, String fileName) {
			this.urlStr = urlStr;
			this.threadNum = threadNum;
			this.fileName = fileName;
		}

		@Override
		public void run() {
			FileDownloadThread[] fds = new FileDownloadThread[threadNum];
			try {
				URL url = new URL(urlStr);
				URLConnection conn = url.openConnection();
				// 防止返回-1
				InputStream in = conn.getInputStream();
				// 获取下载文件的总大小
				fileSize = conn.getContentLength();
				Log.i("bb", "======================fileSize:" + fileSize);
				// 计算每个线程要下载的数据量
				blockSize = fileSize / threadNum;
				// 解决整除后百分比计算误差
				downloadSizeMore = (fileSize % threadNum);
				File file = new File(fileName);
				for (int i = 0; i < threadNum; i++) {
					Log.i("bb", "======================i:" + i);
					// 启动线程，分别下载自己需要下载的部分
					FileDownloadThread fdt = new FileDownloadThread(url, file,
							i * blockSize, (i + 1) * blockSize - 1);
					fdt.setName("Thread" + i);
					fdt.start();
					fds[i] = fdt;
				}
				boolean finished = false;
				while (!finished) {
					// 先把整除的余数搞定
					downloadedSize = downloadSizeMore;
					finished = true;
					for (int i = 0; i < fds.length; i++) {
						downloadedSize += fds[i].getDownloadSize();
						if (!fds[i].isFinished()) {
							finished = false;
						}
					}
					handler.sendEmptyMessage(0);
					// 线程暂停一秒
					sleep(100);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
	}
}